<?php

namespace App\Admin\Controllers;

use App\Document;
use App\Http\Controllers\Controller;
use App\Services\DocumentService;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;

class DocumentController extends Controller
{
    protected $service;
    protected $title = '常用资料';

    public function __construct(DocumentService $service)
    {
        $this->service = $service;
    }

    public function index(Content $content)
    {
        return $content
            ->title($this->title)
            ->description(trans('admin.list'))
            ->body($this->grid());
    }

    protected function grid(): Grid
    {
        return $this->service->gridColumns(1);
    }

    protected function form($model = null): Form
    {
        $form = new Form($model);
        $form->deleted(function () use ($model) {
            Document::forgetCache();
            $path = $model->path ?? '';
            storage_unlink($path, 'public');
            admin_storage_unlink($path);
        });
        return $form;
    }

    /**
     * @param $id
     * @return JsonResponse
     * @throws AuthorizationException
     */
    public function destroy($id): JsonResponse
    {
        $model = Document::query()->findOrFail($id);
        $this->authorize('destroy', $model);
        return $this->form($model)->destroy($id);
    }
}
